import { reqUserLogin, reqUserLogout } from "@/api";
const state = {
  userInfo: {
    // name: '',
    // token:''
    name: localStorage.getItem("userName"),
    token: localStorage.getItem("token"),
  },
};
const actions = {
  // 1.用户登录
  async userLogin({ commit }, user) {
    const result = await reqUserLogin(user);
    if (result.code === 200) {
      // console.log('userLogin',result)
      localStorage.setItem("userName", result.data.name);
      localStorage.setItem("token", result.data.token);
      commit("SAVE_USER_INFO", result.data);
    } else {
      console.log("登陆失败...");
    }
  },
  // 2. 用户退出
  async userLogout({ commit }) {
    const result = await reqUserLogout();
    if (result.code === 200) {
      localStorage.removeItem("userName");
      localStorage.removeItem("token");
      commit("REMOVE_USER_INFO");
    }
  },
};
const mutations = {
  // 1. 保存用户数据
  SAVE_USER_INFO(state, payload) {
    state.userInfo.name = payload.name;
    state.userInfo.token = payload.token;
  },
  // 2. 清空用户数据
  REMOVE_USER_INFO(state) {
    state.userInfo.name = "";
    state.userInfo.token = "";
  },
};
const getters = {};

export default {
  namespaced: true, // 开启命名空间 以区分不同的模块
  state,
  actions,
  mutations,
  getters,
};
